package com.cby.jetpack.sample.paging3.data.repository

import androidx.paging.PagingSource
import com.cby.jetpack.sample.paging3.bean.GankApiResponse
import com.cby.jetpack.sample.paging3.bean.GankGirlBean

/**
 * @description: GankDataSource
 *
 * @author ChenBaoyang
 * @date 8/12/21 11:29
 */
class GankGirlDataSource : PagingSource<Int, GankGirlBean>() {

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, GankGirlBean> {
        return try {

            //页码未定义置为1
            val currentPage: Int = params.key ?: 1
            //仓库层请求数据
            val gankApiResponse: GankApiResponse<List<GankGirlBean>>? = GankGirlRepository().loadData(currentPage)
            //当前页码 小于 总页码 页面加1
            val nextPage = if (currentPage < gankApiResponse?.page_count?:0) {
                currentPage + 1
            } else {
                //没有更多数据
                null
            }
            if (gankApiResponse != null) {
                LoadResult.Page(
                    data = gankApiResponse.data,
                    prevKey = null,
                    nextKey = nextPage
                )
            } else {
                LoadResult.Error(throwable = Throwable())
            }
        } catch (e: Exception) {
            LoadResult.Error(throwable = e)
        }
    }

}